/**
 * Cookie解析调试脚本
 * 用于测试和调试不同格式的Cookie解析逻辑
 */

const crypto = require('crypto');

// 模拟Egg.js的Cookie签名逻辑
function signCookie(value, secret) {
  const hmac = crypto.createHmac('sha1', secret);
  hmac.update(value);
  return value + '.' + hmac.digest('base64').replace(/\=+$/, '');
}

function unsignCookie(signedValue, secret) {
  const parts = signedValue.split('.');
  if (parts.length !== 2) return false;

  const value = parts[0];
  const signature = parts[1];

  const hmac = crypto.createHmac('sha1', secret);
  hmac.update(value);
  const expectedSignature = hmac.digest('base64').replace(/\=+$/, '');

  return signature === expectedSignature ? value : false;
}

function testCookieParsing() {
  console.log('🧪 Cookie解析调试测试\n');

  // 测试数据
  const sessionId = 'abc123def-456-789-012-345678901234';
  const secret = 'test_secret_key';

  console.log('📝 原始SessionId:', sessionId);
  console.log('🔑 签名密钥:', secret);

  // 测试1: 签名Cookie
  console.log('\n--- 测试1: 签名Cookie ---');
  const signedCookie = signCookie(sessionId, secret);
  console.log('签名后:', signedCookie);

  const unsignedValue = unsignCookie(signedCookie, secret);
  console.log('验证签名:', unsignedValue);
  console.log('签名验证结果:', unsignedValue === sessionId ? '✅ 成功' : '❌ 失败');

  // 测试2: Base64编码
  console.log('\n--- 测试2: Base64编码 ---');
  const base64Encoded = Buffer.from(sessionId).toString('base64');
  console.log('Base64编码:', base64Encoded);

  const base64Decoded = Buffer.from(base64Encoded, 'base64').toString('utf8');
  console.log('Base64解码:', base64Decoded);
  console.log('Base64测试结果:', base64Decoded === sessionId ? '✅ 成功' : '❌ 失败');

  // 测试3: JSON编码
  console.log('\n--- 测试3: JSON编码 ---');
  const jsonData = JSON.stringify({ sessionId: sessionId });
  const jsonBase64 = Buffer.from(jsonData).toString('base64');
  console.log('JSON数据:', jsonData);
  console.log('JSON Base64编码:', jsonBase64);

  const jsonDecoded = Buffer.from(jsonBase64, 'base64').toString('utf8');
  const jsonParsed = JSON.parse(jsonDecoded);
  console.log('JSON解码:', jsonDecoded);
  console.log('JSON解析:', jsonParsed);
  console.log('JSON测试结果:', jsonParsed.sessionId === sessionId ? '✅ 成功' : '❌ 失败');

  // 测试4: UUID格式验证
  console.log('\n--- 测试4: UUID格式验证 ---');
  const uuidPattern = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;

  const testUUIDs = [
    'abc123def-456-789-012-345678901234',
    'ABC123DE-F456-789A-BC01-23456789ABCD',
    'invalid-uuid-format',
    '12345678-1234-1234-1234-123456789012'
  ];

  testUUIDs.forEach(uuid => {
    const isValid = uuidPattern.test(uuid);
    console.log(`UUID "${uuid}": ${isValid ? '✅ 有效' : '❌ 无效'}`);
  });

  // 测试5: Cookie字符串解析
  console.log('\n--- 测试5: Cookie字符串解析 ---');
  const cookieStrings = [
    'SSO_SESSION_ID=abc123def-456-789-012-345678901234',
    'SSO_SESSION_ID=abc123def-456-789-012-345678901234.signature; Path=/',
    'other=value; SSO_SESSION_ID=abc123def-456-789-012-345678901234; another=value2',
    'SSO_SESSION_ID=' + base64Encoded + '; Path=/'
  ];

  cookieStrings.forEach((cookieStr, index) => {
    console.log(`\nCookie字符串 ${index + 1}: ${cookieStr}`);

    const cookies = Object.fromEntries(
      cookieStr
        .split(';')
        .map(c => c.trim())
        .filter(Boolean)
        .map(c => {
          const idx = c.indexOf('=');
          const k = idx > -1 ? c.slice(0, idx) : c;
          const v = idx > -1 ? decodeURIComponent(c.slice(idx + 1)) : '';
          return [k, v];
        })
    );

    console.log('解析结果:', cookies);
    console.log('SSO_SESSION_ID:', cookies['SSO_SESSION_ID'] || '未找到');
  });
}

// 运行测试
testCookieParsing();
